//
//  HNHappyTimeTalkVC.m
//  XDEducation
//
//  Created by 星道 on 17/8/3.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HNHappyTimeTalkVC.h"
#import "HNHappyTimeFMDB.h"
#import "HNHappyTimeTalkModel.h"
#import "HNHappyTimeTalkMyCell.h"
#import "HNHappyTimeTalkOtherCell.h"
@interface HNHappyTimeTalkVC ()<UITableViewDelegate,UITableViewDataSource>
/** 聊天界面 */
@property (strong, nonatomic) IBOutlet UITableView *tableView;
/** 数据库操作类 */
@property (nonatomic, strong) HNHappyTimeFMDB *FMDB;
// 聊天记录
@property (nonatomic, strong) NSMutableArray <HNHappyTimeTalkModel *>*DataArr;
/** 发送消息的按钮 */
@property (strong, nonatomic) IBOutlet UIButton *SendMessBtn;
/** 输入框 */
@property (strong, nonatomic) IBOutlet UITextField *ContentTf;
@end

@implementation HNHappyTimeTalkVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = self.Name;

    // 发送按钮状态切换
    [self.SendMessBtn setBackgroundImage:[self CreateImageWithColor:UIColor(240, 240, 240)] forState:(UIControlStateNormal)];
    [self.SendMessBtn setBackgroundImage:[self CreateImageWithColor:ThemeColor] forState:(UIControlStateSelected)];

    // 输入框字数监听
    [self.ContentTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    [self.tableView registerNib:[UINib nibWithNibName:[HNHappyTimeTalkMyCell description] bundle:nil] forCellReuseIdentifier:@"MyCell"];
    [self.tableView registerNib:[UINib nibWithNibName:[HNHappyTimeTalkOtherCell description] bundle:nil] forCellReuseIdentifier:@"OtherCell"];

    self.tableView.estimatedRowHeight = 250;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    [self MgrFMDBStatus];

}



#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HNHappyTimeTalkModel *Model = self.DataArr[indexPath.row];
    NSLog(@"%@,%@",[Model.Uid stringValue],[AccountTool shareAccountTool].currentAccount.uid);
    if ([[Model.Uid stringValue] isEqualToString:[AccountTool shareAccountTool].currentAccount.uid])
    {
        // 实例化别人
        HNHappyTimeTalkMyCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
        // 点语法
        Cell.Model = Model;

        return Cell;
    }
    else
    {

        // 实例化我的Cell
        HNHappyTimeTalkOtherCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"OtherCell" forIndexPath:indexPath];
        // 点语法
        Cell.Model = Model;

        return Cell;
    }
}

#pragma mark - 方法
/** 颜色转图片 */
- (UIImage*)CreateImageWithColor:(UIColor*)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

/** TableView滚动到最底部 */
- (void)TableViewToBottom:(BOOL)Animated
{
    NSInteger s = [self.tableView numberOfSections];  //有多少组
    if (s<1) return;  //无数据时不执行 要不会crash
    NSInteger r = [self.tableView numberOfRowsInSection:s-1]; //最后一组有多少行
    if (r<1) return;
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];  //取最后一行数据
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:Animated]; //滚动到最后一行
}

#pragma mark - 点击事件
/** 发送信息 */
- (IBAction)SendMessage:(UIButton *)sender
{
    [self MgrInsertData];
}


#pragma mark - 处理事件
/** 处理数据的打开状态 */
- (void)MgrFMDBStatus
{
    [self MgrFMDHSelectData];
}

/** 数据库打开成功就开始查找数据 */
- (void)MgrFMDHSelectData
{
    /** 查询数据之后赋值 */
    [self.DataArr addObjectsFromArray:[self.FMDB QueryData]];

    [self TableViewToBottom:YES];
    [self.tableView reloadData];
}

/** 返回 */
- (void)Close
{
    // 这里的错误原因是数据库打不开
    [MBProgressHUD showError:@"聊天模块初始失败"];
    /** 关闭数据库 */
    //    [self.FMDB CloseSql];
    [self.navigationController popViewControllerAnimated:YES];
}

/** 处理添加数据 */
- (void)MgrInsertData
{
    // 数据添加成功，刷新表单
    [self.FMDB InsertDataWithStr:self.ContentTf.text Complete:^(BOOL IsRight, HNHappyTimeTalkModel *Model) {
        if (IsRight)
        {
            // 清空输入框
            self.ContentTf.text = @"";
            // 设置按钮状态
            [self textFieldDidChange:self.ContentTf];
            // 添加数据
            [self.DataArr addObject:Model];
            // 刷新
            [self.tableView reloadData];
            // 滚动到底部
            [self TableViewToBottom:YES];

        }
        else
        {
            [MBProgressHUD showError:@"消息发送失败"];
        }
    }];
}

#pragma mark - TextField代理
- (void)textFieldDidChange:(UITextField *)textField
{
    self.SendMessBtn.selected = textField.text.length;
    self.SendMessBtn.userInteractionEnabled = textField.text.length;
}

#pragma mark - Setter
- (HNHappyTimeFMDB *)FMDB
{
    if (!_FMDB)
    {
        _FMDB = [[HNHappyTimeFMDB alloc] initWithID:self.Uid];
    }
    return _FMDB;
}

- (NSMutableArray<HNHappyTimeTalkModel *> *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}
@end
